package com.example.main;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main06 {

    private final static AtomicBoolean EXECUTE=new AtomicBoolean(true);

    public static void main(String[] args) {
        new Thread(new Task()).start();
//        new Thread(new Task()).start();
//        new Thread(new Task()).start();

        try {
            TimeUnit.SECONDS.sleep(9);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("==========: "+ EXECUTE.get());
    }

    public static void doSomething(){


        if (EXECUTE.compareAndSet(true,false)){
            System.out.println(Thread.currentThread().getName()+" : 执行步骤1");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" : 执行步骤1完成");
            EXECUTE.set(true);
            synchronized (EXECUTE){
                System.out.println(Thread.currentThread().getName()+" : 准备唤醒其他线程");
                EXECUTE.notifyAll();
                System.out.println(Thread.currentThread().getName()+" : 唤醒其他线程成功");
            }
        }else {
            System.out.println(Thread.currentThread().getName()+" : 等待步骤1执行完成");
            try {
                synchronized (EXECUTE){
                    System.out.println(Thread.currentThread().getName()+" : 阻塞等待步骤1执行完成");
                    EXECUTE.wait(30000);
                    System.out.println(Thread.currentThread().getName()+" : 阻塞被唤醒");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" : 其他线程执行步骤1完成");
        }

        System.out.println(Thread.currentThread().getName()+" : 执行步骤2");
    }


    public static class Task implements Runnable{
        @Override
        public void run() {
            doSomething();
        }
    }
}
